package cn.edu.scau.cmi.ema.service;

import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;


import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.persistence.Query;
import java.util.Iterator;
@Service("TasteService")
@Transactional

public class TasteServiceImpl extends CmiEmaService implements TasteService {
	public TasteServiceImpl() {
	}

	@Transactional
	public Taste saveTaste(Taste taste) {
		Set<Food> existingFoodsForTaste = new HashSet<Food>();

		Set<Food> selectedFoodsForTaste = taste.getFoodsForTaste();

		if (taste.getId() == null) {

			Taste existingTaste = tasteDAO.findTasteByPhysicalPrimaryKey(taste.getName());

			if (isEquals(taste, existingTaste)) {
				return existingTaste;
			}

			taste = tasteDAO.store(taste);
			tasteDAO.flush();

			for (Food relatedFood : selectedFoodsForTaste) {
				relatedFood.setTaste(taste);
				foodDAO.store(relatedFood);
			}
		} else {
			Taste existingTaste = tasteDAO.findTasteByPrimaryKey(taste.getId());

			existingFoodsForTaste = existingTaste.getFoodsForTaste();

			Set<Food> prepareDeleteFoodsForTaste = new HashSet<Food>();
			Set<Food> prepareAddFoodsForTaste = new HashSet<Food>();

			prepareDeleteFoodsForTaste.addAll(selectedFoodsForTaste);
			prepareDeleteFoodsForTaste.addAll(existingFoodsForTaste);

			prepareAddFoodsForTaste.addAll(selectedFoodsForTaste);
			prepareAddFoodsForTaste.addAll(existingFoodsForTaste);

			prepareDeleteFoodsForTaste.removeAll(selectedFoodsForTaste);
			prepareAddFoodsForTaste.removeAll(existingFoodsForTaste);

			for (Food relatedFood : prepareAddFoodsForTaste) {
				relatedFood.setTaste(taste);
				foodDAO.store(relatedFood);
			}

			for (Food relatedFood : prepareDeleteFoodsForTaste) {
				relatedFood.setTaste(null);
				foodDAO.store(relatedFood);
			}
			taste = tasteDAO.store(taste);
			tasteDAO.flush();
		}

		foodDAO.flush();
		return taste;
	}

	public void deleteTaste(Taste taste) {
		tasteDAO.remove(taste);
		tasteDAO.flush();
	}

	@Transactional
	public void deleteTastes(Set<Integer> deleteTastesId) {
		Query query = tasteDAO.createNamedQuery("deleteTastesById", -1, -1);
		query.setParameter(1, deleteTastesId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Taste> loadTastes() {
		return tasteDAO.findAllTastes();

	}

	@Transactional
	public Set<Taste> loadReferenceTastes(Set<Taste> tastes) {
		Iterator<Taste> tastesIterator = tastes.iterator();
		Set<Taste> referencedTastes = new HashSet<>();
		while (tastesIterator.hasNext()) {
			Taste currentTaste = tastesIterator.next();

			if (!currentTaste.getFoodsForTaste().isEmpty()) {
				referencedTastes.add(currentTaste);
				continue;
			}
		}
		return referencedTastes;
	}

	public Set<Taste> loadTastesByIdSet(Set<Integer> tasteIdSet) {

		Iterator<Integer> tasteIdIterator = tasteIdSet.iterator();
		Set<Taste> tasteSet = new HashSet<>();
		while (tasteIdIterator.hasNext()) {
			Integer id = tasteIdIterator.next();
			Taste currentTaste = tasteDAO.findTasteById(id);
			tasteSet.add(currentTaste);
		}
		return tasteSet;
	}

	@Transactional
	public List<Taste> findAllTastes(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Taste>(tasteDAO.findAllTastes(startResult, maxRows));
	}

	@Transactional
	public Taste findTasteByPrimaryKey(Integer id) {
		return tasteDAO.findTasteByPrimaryKey(id);
	}

	@Transactional
	public Integer countTastes() {
		return ((Long) tasteDAO.createQuerySingleResult("select count(o) from Taste o").getSingleResult()).intValue();
	}

	@Transactional
	public Integer countTastes(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Taste.class);
		return ((Long) tasteDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 * 
	 */
	@Transactional
	public Integer countTastesByName(String queryName) {
		Query query = tasteDAO.createNamedQuery("countTastesByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countTastesByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Taste.class);
		Session session = entityManager.unwrap(Session.class);
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadTasteObjectReferencedSet(Taste taste) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();

		Set<Integer> foodsIds = new HashSet<Integer>();
		for (Food obj : taste.getFoodsForTaste()) {

			foodsIds.add(obj.getId());
		}
		objectReferencedSetMap.put("foodsIds", foodsIds);

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadTasteClassReferencedSet(Taste taste) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("foods", foodDAO.findAllFoods());

		return classReferencedSetMap;
	}

	public boolean isEquals(Taste taste, Object obj) {
		if (obj == taste)
			return true;
		if (!(obj instanceof Taste))
			return false;
		Taste comparedTaste = (Taste) obj;
		if (!CheckPropertyEqual(taste.getName(), comparedTaste.getName())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

